package cs551.listtracker;

/*
 * Copyright (C) 2013 Surviving with Android (http://www.survivingwithandroid.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Parcel;
import android.support.v4.widget.SlidingPaneLayout;
import android.view.View;
import cs551.listtracker.ListFragment.ItemListener;
import cs551.listtracker.ListofListsFragment.ListListener;
import cs551.listtracker.structure.History;
import cs551.listtracker.structure.ListContainer;
import cs551.listtracker.structure.ListItem;
import cs551.listtracker.structure.ShoppingList;

public class MainActivity extends Activity implements ListListener,
		ItemListener {
	SlidingPaneLayout pane;
	protected History history;
	protected ListContainer listContainer;
	protected List<ShoppingList> shoppingListList;
	// boolean prefs_usedb;
	// boolean prefs_autodelete;
	// boolean prefs_costcomparison;
	public SharedPreferences settings;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Restore preferences
		settings = getSharedPreferences("preferences",
				Context.MODE_WORLD_WRITEABLE);

		fileInit();

		setContentView(R.layout.activity_main);

		pane = (SlidingPaneLayout) findViewById(R.id.sp);
		pane.setPanelSlideListener(new PaneListener());

		if (!pane.isSlideable()) {
			getFragmentManager().findFragmentById(R.id.leftpane)
					.setHasOptionsMenu(false);
			getFragmentManager().findFragmentById(R.id.rightpane)
					.setHasOptionsMenu(true);
		}
		// pane.openPane();

	}

	void init() {

		if (shoppingListList.size() == 0) {
			shoppingListList.add(new ShoppingList("List One"));

		}

		((ListListener) this).onChangeList(shoppingListList.get(0));
		getActionBar().setTitle(shoppingListList.get(0).title);
	}

	void populateTestData() {

		ShoppingList list1 = new ShoppingList("Waitrose");
		list1.shopList.add(new ListItem("Brown Bread", 1, 0.95));
		list1.shopList.add(new ListItem("Skimmed Milk, 2L", 1, 0.76));
		list1.shopList.add(new ListItem("Oranges", 8, 0.39));
		list1.shopList.add(new ListItem("Cat food", 1, 4.99));
		shoppingListList.add(list1);

		ShoppingList list2 = new ShoppingList("James' List");
		list2.shopList.add(new ListItem("Emergency toothbrush", 1, 2.50));
		list2.shopList.add(new ListItem("Socks", 1, 0));
		list2.shopList.add(new ListItem("Biscuit", 1, 0.20));
		shoppingListList.add(list2);

		ShoppingList list3 = new ShoppingList("Dinner for Parents");
		list3.shopList.add(new ListItem("Ingredient", 2, 1));
		list3.shopList.add(new ListItem("Ingredient2", 2, 1));
		list3.shopList.add(new ListItem("Ingredient3", 1, 1));
		shoppingListList.add(list3);

		((ListListener) this).onChangeList(shoppingListList.get(0));
		getActionBar().setTitle(shoppingListList.get(0).title);

	}

	void fileInit() {
		File listfile = getBaseContext().getFileStreamPath("Lists");

		try {
			InputStream fis = null;
			try {
				fis = openFileInput(listfile.getName());
				byte[] bytes = toByteArray(fis, (int) listfile.length());

				Parcel parcel = Parcel.obtain();
				parcel.unmarshall(bytes, 0, bytes.length);
				parcel.setDataPosition(0); // this is extremely important!
				listContainer = new ListContainer(parcel);
				shoppingListList = listContainer.lists;
				parcel.recycle();
				fis.close();

			} finally {
			}
		} catch (FileNotFoundException e) {
			System.out.println("Lists File not found");
			listContainer = new ListContainer();
			shoppingListList = listContainer.lists;
		}

		catch (IOException e) {
		}

		File histfile = getBaseContext().getFileStreamPath("History");

		try {
			InputStream fis = null;
			try {

				fis = openFileInput(histfile.getName());
				byte[] bytes = toByteArray(fis, (int) histfile.length());

				Parcel parcel = Parcel.obtain();
				parcel.unmarshall(bytes, 0, bytes.length);
				parcel.setDataPosition(0); // this is extremely important!
				history = new History(parcel);
				parcel.recycle();
				fis.close();

			} finally {
			}
		} catch (FileNotFoundException e) {
			System.out.println("History File not found");
			history = new History();
		}

		catch (IOException e) {
		}
	}

	public static byte[] toByteArray(final InputStream input, final int size)
			throws IOException {

		if (size < 0) {
			throw new IllegalArgumentException(
					"Size must be equal or greater than zero: " + size);
		}

		if (size == 0) {
			return new byte[0];
		}

		final byte[] data = new byte[size];
		int offset = 0;
		int readed;

		while (offset < size
				&& (readed = input.read(data, offset, size - offset)) != -1) {
			offset += readed;
		}
		if (offset != size) {
			throw new IOException("Unexpected readed size. current: " + offset
					+ ", excepted: " + size);
		}

		return data;
	}

	private class PaneListener implements SlidingPaneLayout.PanelSlideListener {

		@Override
		public void onPanelClosed(View view) {

			if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {

				getActionBar().setDisplayHomeAsUpEnabled(true);
				// getActionBar().setHomeButtonEnabled(true);
				getFragmentManager().findFragmentById(R.id.leftpane)
						.setHasOptionsMenu(false);
				getFragmentManager().findFragmentById(R.id.rightpane)
						.setHasOptionsMenu(true);

			} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
				getFragmentManager().findFragmentById(R.id.leftpane)
						.setHasOptionsMenu(true);
				getFragmentManager().findFragmentById(R.id.rightpane)
						.setHasOptionsMenu(true);
			}
		}

		@Override
		public void onPanelOpened(View view) {

			if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {

				getActionBar().setDisplayHomeAsUpEnabled(false);
				// getActionBar().setHomeButtonEnabled(true);
				getFragmentManager().findFragmentById(R.id.leftpane)
						.setHasOptionsMenu(true);
				getFragmentManager().findFragmentById(R.id.rightpane)
						.setHasOptionsMenu(false);
			} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
				getFragmentManager().findFragmentById(R.id.leftpane)
						.setHasOptionsMenu(true);
				getFragmentManager().findFragmentById(R.id.rightpane)
						.setHasOptionsMenu(true);
			}
		}

		@Override
		public void onPanelSlide(View view, float arg1) {
			// System.out.println("Panel sliding");
		}

	}

	@Override
	public void onChangeList(ShoppingList shoppinglist) {
		// We get notified when user clicks on a list in the LoLFragment
		shoppinglist.hideChecked(settings.getBoolean("autodelete", false));

		ListFragment f = (ListFragment) getFragmentManager().findFragmentById(
				R.id.rightpane);
		f.setList(shoppinglist);
		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
			pane.closePane();
	}

	@Override
	public void onChangeList() {
		ListFragment f = (ListFragment) getFragmentManager().findFragmentById(
				R.id.rightpane);
		f.la.notifyDataSetChanged();
	}

	@Override
	public void onUpdateList() {
		// We get notified when user clicks on a list in the LoLFragment

		ListofListsFragment f = (ListofListsFragment) getFragmentManager()
				.findFragmentById(R.id.leftpane);
		f.updateLists();
		fileout();

	}

	@Override
	protected void onPause() {

		fileout();

		super.onPause();

	}

	private void fileout() {
		SharedPreferences settings = getSharedPreferences("preferences",
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("autodelete",
				settings.getBoolean("autodelete", false));
		editor.putBoolean("usedb", settings.getBoolean("usedb", false));
		editor.putBoolean("costcomparison",
				settings.getBoolean("costcomparison", false));

		// Commit the edits!
		editor.apply();

		FileOutputStream fos;
		try {

			Parcel parcel = Parcel.obtain();
			history.writeToParcel(parcel, 0);

			fos = openFileOutput("History", Context.MODE_PRIVATE);
			fos.write(parcel.marshall());
			fos.close();
			parcel.recycle();

			parcel = Parcel.obtain();
			listContainer.writeToParcel(parcel, 0);

			fos = openFileOutput("Lists", Context.MODE_PRIVATE);
			fos.write(parcel.marshall());
			fos.close();

			parcel.recycle();

		} catch (Exception e) {

		}
	}

	// Parcel parcel = Parcel.obtain();
	// list.writeToParcel(parcel, 0);
	//
	// ContentValues cv = new ContentValues();
	// cv.put(KEY_LIST, parcel.marshall());
	//
	// parcel.recycle();
	//
	// return mDb.update(DATABASE_TABLE, cv, KEY_ROWID + "=" + rowId, null) > 0;

}
